package ua.kharkov.khpi.tarasenko.bach.core.db;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

	private static final Logger LOG = Logger.getLogger(HibernateUtil.class);
	private static final SessionFactory sessionFactory;

	static {
		try {
			Configuration configuration = new Configuration();
			configuration.configure("hibernate.cfg.xml");
			ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()
					.applySettings(configuration.getProperties());
			sessionFactory = configuration
					.buildSessionFactory(serviceRegistryBuilder
							.buildServiceRegistry());

		} catch (Throwable th) {
			LOG.fatal("Can't initialize HibernateUtils!", th);
			throw new ExceptionInInitializerError(th);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static Session beginTransaction() {
		Session hibernateSession = HibernateUtil.getSession();
		hibernateSession.beginTransaction();
		return hibernateSession;
	}

	public static void commitTransaction(Transaction transaction) {
		transaction.commit();
	}

	public static void rollbackTransaction(Transaction transaction) {
		transaction.rollback();
	}

	public static void closeSession(Session session) {
		session.close();
	}

	public static Session getSession() {
		Session hibernateSession = sessionFactory.openSession();
		return hibernateSession;
	}
}